﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Client;
using SiemensOPC;
using VswService_V7.Config;
using VswService_V7.DataBase.Tables;
using System.Data;
using VswService_V7.Utility;

namespace VswService_V7.OPC.DB
{
    public class StripInfoAddressDbData : SubscriptionDbDataBase
    {
        string askStripNo = "0";
        List<string> _stripTaskRecipeList;
        public StripInfoAddressDbData(SimaticOPCClient opc, NodeConfig nodes) : base(opc, nodes)
        {
            _stripTaskRecipeList = new List<string>();
        }
        public override void CreateSubscription()
        {
            try
            {
                opcServer.QuickAddMonitorItem(opcNodes.StripInfoAddress.GrpoupName,
                    opcNodes.StripInfoAddress.PublishTime, opcNodes.StripInfoAddress.SampleTime,
                    opcNodes.StripInfoAddress.GetNodeAddress(), opcNodes.StripInfoAddress.GetNodeDisplayName(),
                    SubscriptionHandler_StripInfoAddress);

                opcServer.QuickAddMonitorItem(opcNodes.StripInfoAskAddress.GrpoupName,
                    opcNodes.StripInfoAskAddress.PublishTime, opcNodes.StripInfoAskAddress.SampleTime,
                    opcNodes.StripInfoAskAddress.GetNodeAddress(), opcNodes.StripInfoAskAddress.GetNodeDisplayName(),
                    SubscriptionHandler_StripInfoAskAddress);

                opcServer.QuickAddMonitorItem(opcNodes.StripInfoRspAddress.GrpoupName,
                    opcNodes.StripInfoRspAddress.PublishTime, opcNodes.StripInfoRspAddress.SampleTime,
                    opcNodes.StripInfoRspAddress.GetNodeAddress(), opcNodes.StripInfoRspAddress.GetNodeDisplayName(),
                    SubscriptionHandler_StripInfoRspAddress);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("StripInfoAddressDbData CreateSubscription", ex);
                throw (ex);
            }
        }

        private void SubscriptionHandler_StripInfoAddress(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
            if (notification == null || notification.Value.Value == null)
                return;
            if (monitoredItem.DisplayName == "StripsInfoAsk")
            {
                bool ask = false;
                if (bool.TryParse(notification.Value.Value.ToString(), out ask))
                {
                   if (ask)
                    {
                        Console.WriteLine("FGS recipe get ask");
                        _stripTaskRecipeList.Clear();
                        Task.Run(() => HandleNewStripInfo());
                    }
                    else
                    {
                        Console.WriteLine("FGS recipe reply");
                        opcServer.WriteValue("false", opcNodes.StripInfoAddress.StripsInfoRsp);
                    }
                }
            }
        }

        private void SubscriptionHandler_StripInfoAskAddress(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
            if (notification == null || notification.Value.Value == null)
                return;
            if (monitoredItem.DisplayName == "Strip_No")
            {
                try
                {
                    askStripNo = notification.Value.Value.ToString();
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("SubscriptionHandler_StripInfoAskAddress  Strip_No is null", ex);
                    askStripNo = "0";
                }
            }
        }

        private async Task HandleNewStripInfo()
        {
            await Task.Delay(1000);
            try
            {
                DataTable stripTable = STRIP_INFO.SelectUncoiledStripInfo(askStripNo);
                if (stripTable != null && stripTable.Rows.Count > 0)
                {
                    string taskNo = stripTable.Rows[0][STRIP_INFO.fd_taskNo].ToString();
                    DataTable taskTable = TASK_INFO.SelectTaskInfo(taskNo);
                    if (taskTable != null && taskTable.Rows.Count > 0)
                    {
                        string recipeIndex = taskTable.Rows[0][TASK_INFO.fd_recipeNo].ToString();
                        DataTable recipeTable = RECIPE_INFO.SelectRecipeByIndex(recipeIndex);
                        if (recipeTable != null && recipeTable.Rows.Count > 0)
                        {
                            _stripTaskRecipeList.Add(stripTable.Rows[0][STRIP_INFO.fd_batchNoO].ToString());
                            _stripTaskRecipeList.Add(stripTable.Rows[0][STRIP_INFO.fd_batchNoE].ToString());
                            _stripTaskRecipeList.Add(taskTable.Rows[0][TASK_INFO.fd_recipeNo].ToString());
                            _stripTaskRecipeList.Add(taskTable.Rows[0][TASK_INFO.fd_productionStandard].ToString());
                            _stripTaskRecipeList.Add(taskTable.Rows[0][TASK_INFO.fd_batchSampleRule].ToString());
                            _stripTaskRecipeList.Add(taskTable.Rows[0][TASK_INFO.fd_stripSampleRule].ToString());
                            _stripTaskRecipeList.Add(taskTable.Rows[0][TASK_INFO.fd_taskNo].ToString());
                            _stripTaskRecipeList.Add(stripTable.Rows[0][STRIP_INFO.fd_isSpy].ToString());
                            _stripTaskRecipeList.Add(taskTable.Rows[0][STRIP_INFO.fd_stripDurabilityClass].ToString());

                            _stripTaskRecipeList.Add(Formats.ConvertUnit(stripTable.Rows[0][STRIP_INFO.fd_stripThk].ToString(), VswUnit.STRIP_THK_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(stripTable.Rows[0][STRIP_INFO.fd_stripWidth].ToString(), VswUnit.STRIP_WIDTH_L1,0));

                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeNominalLength].ToString(), VswUnit.PIPE_LENGTH_L1, 0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMaxLength].ToString(), VswUnit.PIPE_LENGTH_L1, 0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMinLength].ToString(), VswUnit.PIPE_LENGTH_L1, 0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeNominalOd].ToString(), VswUnit.PIPE_OD_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMaxOd].ToString(), VswUnit.PIPE_OD_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMinOd].ToString(), VswUnit.PIPE_OD_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeNominalThickness].ToString(), VswUnit.PIPE_WT_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_pipeMinThickness].ToString(), VswUnit.PIPE_WT_L1,0));
                            _stripTaskRecipeList.Add(taskTable.Rows[0][TASK_INFO.fd_innerBeadIsremoving].ToString());
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_innerBeadHeight].ToString(), VswUnit.INNER_BEAD_HEIGHT_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_innerBeadDepth].ToString(), VswUnit.INNER_BEAD_Depth_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_ovalityUpLimit].ToString(), VswUnit.PIEP_OVLITY_L1, 0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_bodyStraightness].ToString(), VswUnit.STRAIGHTNESS_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(taskTable.Rows[0][TASK_INFO.fd_endStraightness].ToString(), VswUnit.STRAIGHTNESS_L1,0));

                            _stripTaskRecipeList.Add(Formats.ConvertUnit(recipeTable.Rows[0][RECIPE_INFO.fd_yeildStrength].ToString(), VswUnit.Yeild_Strength_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(recipeTable.Rows[0][RECIPE_INFO.fd_emCuttingSpd].ToString(), VswUnit.EM_Cut_SPD_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(recipeTable.Rows[0][RECIPE_INFO.fd_emChipload].ToString(), VswUnit.EM_CHIPLOAD_L1,0));
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa1Power].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa1Temp].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa1Height].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa1Freq].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa2Power].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa2Temp].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa2Height].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa2Freq].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa3Power].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa3Temp].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa3Height].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa3Freq].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa4Power].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa4Temp].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa4Height].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sa4Freq].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_hfwLineSpeed].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_HfwPower].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_HfwFreq].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_HfwVee_X].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sustCw1].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_sustCw2].ToString());
                            //add
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(recipeTable.Rows[0][RECIPE_INFO.fd_stripWdTarget].ToString(), VswUnit.Strip_WD_Target_L1,0));
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_HfwMode].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_HfwPreHeatPower].ToString());
                            _stripTaskRecipeList.Add(recipeTable.Rows[0][RECIPE_INFO.fd_HfwTemperature].ToString());
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(recipeTable.Rows[0][RECIPE_INFO.fd_HfwSPCGain].ToString(), VswUnit.HFW_SPC_Gain_L1,0));
                            _stripTaskRecipeList.Add(Formats.ConvertUnit(recipeTable.Rows[0][RECIPE_INFO.fd_HfwSPCSlope].ToString(), VswUnit.HFW_SPC_Slope_L1,0));
                            foreach(var k in _stripTaskRecipeList)
                            {
                                Console.WriteLine(k);
                            }
                        }
                    }
                }
                if (_stripTaskRecipeList.Count == opcNodes.StripInfoRspAddress.GetNodeAddress().Count)
                {
                    opcServer.WriteValues(_stripTaskRecipeList, opcNodes.StripInfoRspAddress.GetNodeAddress());
                }
                else
                {
                    List<string> errorList = new List<string>();
                    for (int i = 0; i < opcNodes.StripInfoRspAddress.GetNodeAddress().Count; i++)
                        errorList.Add("-1");
                    opcServer.WriteValues(errorList, opcNodes.StripInfoRspAddress.GetNodeAddress());
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("HandleNewStripInfo", ex);
            }
            opcServer.WriteValue("true", opcNodes.StripInfoAddress.StripsInfoRsp);

        }

        private void SubscriptionHandler_StripInfoRspAddress(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
            if (notification == null || notification.Value.Value == null)
                return;
        }
    }
}
